package com.apes.hr.base.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.model.Job;
import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.model.WorkPostGroup;
import com.apes.hr.base.repository.*;
import com.apes.hr.recruit.repository.RecruitChannelRepository;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.model.EnumerationType;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationTypeRepository;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.repository.PostRepository;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.rbac.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：HR-人员信息
 *
 * @author HuJianLin
 * @create 2018-04-28 14:35
 */
@Service("hrEmployeeService")
public class EmployeeService extends DomainService {
    @Autowired
    public EmployeeRepository employeeRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    EnumerationTypeRepository enumerationTypeRepository;

    @Autowired
    AreaRepository areaRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    SequenceService sequenceService;

    @Autowired
    HrDao hrDao;

    @Autowired
    TransferRecordRepository transferRecordRepository;

    @Autowired
    RecruitChannelRepository recruitChannelRepository;

    @Autowired
    SkillTypeRepository skillTypeRepository;

    @Autowired
    TalentPoolRepository talentPoolRepository;
    @Autowired
    PostRepository postRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    ApesLoggerService apesLoggerService;


    public Employee save(SimpleRequest request){
        Employee employee = request.getO(Employee.class);
        return createAndUpdate(employee);
    }


    public Employee createAndUpdate(Employee employee){
        if(employee.getId() == null){
            String code = sequenceService.getId("PARTY_Employee" );
            employee.setId("0"+code);
            employee.setCreateDate(new Date());
        }

        employee.setState("create");

        // 设置员工信息
        setEmployeeData(employee);

//        List<Employee> employeeList = findByIdCard(employee.getIdCard());
//        if (employeeList != null) throw new RuntimeException("该身份证已经被"+employeeList.get(0).getName()+"使用！");
        return employeeRepository.saveAndFlush(employee);
    }

    public void adjustEmployee(Employee employee){
        // 设置员工信息
        setEmployeeData(employee);
        employeeRepository.saveAndFlush(employee);
    }

    /**
     * 处理地址信息，岗位信息
     * @param employee
     */
    private void setEmployeeData(Employee employee) {
        // 获取 户籍.区县
        Area regCounty = employee.getRegCounty();
        if(regCounty!=null){
            // 获取 户籍.城市编码
            String regCityId = regCounty.getParent();
            // 查找注册城市
            Area regCity = areaRepository.findOne(regCityId);
            // 设置 户籍.城市
            employee.setRegCity(regCity);
            String regProvinceId = regCity.getParent();
            // 设置 户籍.省份
            Area regProvince = areaRepository.findOne(regProvinceId);
            employee.setRegProvince(regProvince);
        }
        // 获取 居住.区县
        Area livingCounty = employee.getLivingCounty();
        if(livingCounty!=null){
            // 获取 居住.城市编码
            String livingCityId = livingCounty.getParent();
            // 查找 居住.城市
            Area livingCity = areaRepository.findOne(livingCityId);
            // 设置 居住.城市
            employee.setLivingCity(livingCity);
            String livingProvinceId = livingCity.getParent();
            // 设置 居住.省份
            Area livingProvince = areaRepository.findOne(livingProvinceId);
            employee.setLivingProvince(livingProvince);
        }

        WorkPost post = employee.getPost();
        Job job =  employee.getJob();
        if(post!=null && job!=null){
            if(post != null){
                if(post.getName().equals(job.getName())){
                    employee.setPostDescribe(post.getName() + employee.getRank().getName());
                } else {
                    employee.setPostDescribe(post.getName() + job.getName() + employee.getRank().getName());
                }
            } else {
                employee.setPostDescribe(job.getName() + employee.getRank().getName());
            }
        }

    }

    public Employee update(SimpleRequest request){
        Employee employee = request.getO(Employee.class);
        setEmployeeData(employee);      // 设置员工信息
        if (employee.getEmployeeState().getId().equals("000417")) recordMobile(employee);   //员工状态为待入职检查手机号码是否有修改
        return employeeRepository.saveAndFlush(employee);
    }

    /**
     * 记录手机号码修改写入日志（仅员工状态待入职使用）
     * @param getEmploye
     */
    public void recordMobile(Employee getEmploye){
        Employee employee = employeeRepository.findOne(getEmploye.getId());
        if (!getEmploye.getMobileNumber().equals(employee.getMobileNumber())){
            //写入日志
            apesLoggerService.sendSynEvent("event:ir.logger.create", MapUtil.mapper("businessType", "Employee",
                    "businessKey", employee.getId(), "operate", "将手机号码"+employee.getMobileNumber()+"改成"+getEmploye.getMobileNumber(), "operator_id", 1));
        }

    }

    /**
     * 功能：删除
     * @param request
     */
    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Employee employees = employeeRepository.findOne(id);
        if (employees == null) throw new RuntimeException("人员档案：" + id + " 在系统中不存在。");
        employees.setState("delete");
        employeeRepository.saveAndFlush(employees);
        //employeeRepository.delete(employes);
        return "删除成功！";
    }
    /**
     * 功能：查询 更新 时间戳
     * @param
     */
    @Listener(topic = "event:hr.employee.findByLastUpdateStamp")
    public List<Employee> findByLastUpdateStamp(Date time) {
        List<Employee> listEmployee = employeeRepository.findByLastUpdatedStampGreaterThanOrderByLastUpdatedStampDesc(time);
        return listEmployee;
    }

    /**
     * 功能：分页查询员工
     * @param request

    public Page<Employee> findAll(SimpleRequest request) {
    List<Map> filters = request.get("condition");
    JSONObject djzt = new JSONObject();
    djzt.put("field","state");
    djzt.put("operator","NE");
    djzt.put("value","delete");
    filters.add(djzt);
    Sort sort = new Sort(Sort.Direction.DESC, "id");
    return employeeRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }
     */

    /**
     * 查询部门在职员工
     * @param request
     * @return
     */
    public Page<Employee> findByWorkBranch(SimpleRequest request){
        List<Map> filters = request.get("condition");
        String branch = new String();
        for (Map map : filters) {
            branch = map.get("value").toString();
        }
        branch = branch.substring(2,branch.length()-2);
        return employeeRepository.findByWorkBranch(branch,PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 功能：分页查询可入职员工
     * @param request
     */
    public Page<Employee> findByApplyJob(SimpleRequest request) {
        String key = "";
        key = request.get("key");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return employeeRepository.findByApplyJob(key,"000089",PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 功能：分页查询在职员工转换为PartyRole
     * @param request
     */
    public Page<Map> findAllEmployeeTransPartyRole(SimpleRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        JSONObject jo = request.getJO();
        String value = "";
        if(!Objects.isNull(request.getJO().get("key"))){
            value = request.get("key");
        }else {
            List<Map> filters = request.get("condition");
            if (!filters.isEmpty() || filters.size()!= 0){
                value = (String) filters.get(0).get("value");
            }
        }
        return employeeRepository.findAllTransPartyRole(PageRequest.of(request.get("page"), request.get("size"),sort) , value);
    }

    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return

    public Page<Employee> find(SimpleRequest request) {
    String key = "";
    try {
    key = request.get("key");
    return employeeRepository.find(key,PageRequest.of(request.get("page"), request.get("size")) );
    } catch (Exception e) {
    return  employeeRepository.findAll( PageRequest.of(request.get("page"), request.get("size")));
    }
    }
     */

    public Employee findOne(SimpleRequest request){
        Employee employe = employeeRepository.findOne((String) request.get("id"));
        if(employe == null){
            List<Employee> employes = employeeRepository.findAllById((String) request.get("id"));
            if(!employes.isEmpty()) {
                employe = employes.stream().findFirst().get();
            }
        }
        return employe;
    }


    public WorkPostGroup findName(SimpleRequest request){
        List<Employee> name = employeeRepository.findByName((String) request.get("name"));
        if(name.size() != 1 ) throw new RuntimeException("无法找到当前人员："+(String) request.get("name"));
        Employee employee = name.get(0);
        WorkPostGroup postGroup = employee.getPost().getPostGroup();
        return postGroup;
    }
    /*
     *  查找不能接受的企业行为类型
     */
//    public Page<Enumeration> findUnacceptable(SimpleRequest request) {
//        EnumerationType enumerationType = enumerationTypeRepository.findOne("unacceptable");
//        return enumerationRepository.findByType(enumerationType,PageRequest.of(request.get("page"), request.get("size")));
//    }

    /*
     *  查询民族
     */
    public Page<Enumeration> findNation(SimpleRequest request) {
        String sKey= request.get("key");
        EnumerationType enumerationType = enumerationTypeRepository.findOne("nation");
        String sEnumerationType = enumerationType.getId();
        if(sKey!=null||sKey !=""){
            return enumerationRepository.findByTypeAndKey(sKey,sEnumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }else {
            return enumerationRepository.findByType(enumerationType,PageRequest.of(request.get("page"), request.get("size")));
        }

    }

    /**
     * 查询在职的员工
     * @param request
     * @return
     */
    public Page<Employee> findByEmployeeState2(SimpleRequest request){
        String key = "";
        Post post = postRepository.findOne(request.getPostId());
        List<PartyRole> roleList = new ArrayList<>();
        List<String> orgIds = SpringManager.getBean(PostService.class).findLocalPermitItems(request.getPostId(), "pp_search", "pt_company");
        if(orgIds.isEmpty()){
            roleList.addAll(partyRoleRepository.findAllCompany());
        }
        orgIds.forEach(s -> {
            roleList.add(partyRoleRepository.findOne(s));
        });
        try {
            key = request.get("key");
            return employeeRepository.findByEmployeeState2(key,"000088",roleList,PageRequest.of(request.get("page"), request.get("size")));
        } catch (Exception e) {
            return  employeeRepository.findAll( PageRequest.of(request.get("page"), request.get("size")));
        }
    }

//    public  List<Employee> findByUser(SimpleRequest request){
//        List<Employee> employeeList = null;
//        Employee employee = employeeRepository.findByIdCard(request.getPerson().getParty().getPerson().getIdCard());
//        Branch branch = employee.getWorkBranch();
//        WorkPost workPost = employee.getPost();
//        if (workPost.getName().equals("店长")||workPost.getName().equals("服务顾问")){
//            employeeList = employeeRepository.findByWorkBranch(branch);
//        }else {
//            employeeList.add(employee);
//        }
//        return employeeList;
//    }

    /**
     * 根据身份证号查询
     * @return
     */
    public Employee findByIdCard( SimpleRequest request ) {
        String idCard = request.get("idCard");
        return employeeRepository.findByIdCard(idCard);
    }

    /**
     * 根据手机号查询
     * @param request
     * @return
     */
    public Employee findByMobileNumber(SimpleRequest request ) {
        String mobileNumber = request.get("mobileNumber");
        if(employeeRepository.findByMobileNumber(mobileNumber).size() != 0) {
            return employeeRepository.findByMobileNumber(mobileNumber).get(0);
        } else{
            return null;
        }
    }

    public Employee findByName(SimpleRequest request ) {
        String name = request.get("name");
        if(employeeRepository.findByName(name).size() != 0) {
            return employeeRepository.findByName(name).stream().findFirst().get();
        } else{
            return null;
        }
    }


    public Map<Object,Object> querySex(SimpleRequest request){
        JSONArray branch = null;
        if(!request.getJO().isEmpty()){
            branch =request.get("BRANCHID");
        }
        List<Map> list = hrDao.querySex(branch);
        Map<Object,Object> map = new HashMap<>();
        list.forEach(lis->{
            map.put(lis.get("SEX"),lis.get("NUM"));
        });
        return map;
    }
    public List queryJobClass(SimpleRequest request){
        JSONArray branch = null;
        if(!request.getJO().isEmpty()){
            branch =request.get("BRANCHID");
        }
        List list = hrDao.queryJobClass(branch);
        return list;
    }
    public List queryYear(SimpleRequest request){
        JSONArray branch = null;
        if(!request.getJO().isEmpty()){
            branch =request.get("BRANCHID");
        }
        List list = hrDao.queryYear(branch);
        return list;
    }
    public Map<Object,Object> queryEducation(SimpleRequest request){
        JSONArray branch = null;
        if(!request.getJO().isEmpty()){
            branch =request.get("BRANCHID");
        }
        List<Map> list = hrDao.queryEducation(branch);
        Map<Object,Object> map = new HashMap<>();
        list.forEach(lis->{
            map.put(lis.get("DEGREE_ID"),lis.get("NUM"));
        });
        return map;
    }
    public Map<Object,Object> queryPostGroup(SimpleRequest request){
        JSONArray branch = null;
        if(!request.getJO().isEmpty()){
            branch =request.get("BRANCHID");
        }
        List<Map> list = hrDao.queryPostGroup(branch);
        Map<Object,Object> map = new HashMap<>();
        list.forEach(lis->{
            map.put(lis.get("POST_GROUP_ID"),lis.get("RETIRE"));
        });
        return map;
    }


//    public void getTransferRecord(SimpleRequest request){
//        transferRecordRepository.findAll();
//    }


    /**
     *  更新手机号码
     * @param request
     * @return
     */
    @Listener(topic = "event:hr.employee.updateMobile")
    public Employee updateMobile(SimpleRequest request) {
        JSONObject jsonObject =request.getJO();
        Party party = (Party) jsonObject.get("party");
        String mobileNumber = jsonObject.getString("mobileNumber");
        Employee employee = employeeRepository.findByParty(party);
        employee.setMobileNumber(mobileNumber);
        return employeeRepository.saveAndFlush(employee);
    }

    public Map  findEmployee(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        JSONObject conditionModel = jo.getJSONObject("conditionModel");
        JSONArray condition = jo.getJSONArray("condition");
        int size = jo.getInteger("size");
        int page = jo.getInteger("page");

        JSONObject param = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        param.put("effectiveDate", conditionModel.getString("rewardDate").substring(0, 10));
        param.put("endDate", conditionModel.getString("rewardEndDate").substring(0, 10));

        // 查询条件
        for (int i = 0; i < condition.size(); i++) {
            if ("workBranch".equals(condition.getJSONObject(i).getString("field")))
                param.put("workBranch", condition.getJSONObject(i).getJSONArray("value"));
            if ("post".equals(condition.getJSONObject(i).getString("field")))
                param.put("post", condition.getJSONObject(i).getJSONArray("value"));
            if ("operation".equals(condition.getJSONObject(i).getString("field")))
                param.put("operation", condition.getJSONObject(i).getJSONArray("value"));
            if ( "name".equals(condition.getJSONObject(i).getString("field")) )
                param.put("name", condition.getJSONObject(i).getString("value"));
        }
        param.put("size", size);
        param.put("page", page);

        int total = Integer.valueOf(hrDao.findEmployeeTotal(param).get(0).get("TOTAL").toString());
        List<Map> employeePage = handleEmployeePage(hrDao.findEmployeePage(param));
        return MapUtil.mapper("total", total,
                                "pages", total/20 ,
                                "size", 20,
                                "elements", 20,
                                "content", employeePage);
    }

    private List handleEmployeePage(List<Map> employee) {
        return employee.stream().map(item ->{
            Map m = new HashMap();
            m.put("id", item.get("ID"));

            m.put("name", item.get("NAME"));
            m.put("workBranch", MapUtil.mapper("id", item.get("WORK_BRANCH_ID"),
                                                        "name", item.get("WORK_BRANCH_NAME")));
            m.put("workPost", MapUtil.mapper("id", item.get("POST_ID"),
                    "name", item.get("POST_NAME")));
            m.put("operation", item.get("OPERATION"));
            m.put("entryDate", item.get("ENTRY_DATE"));
            m.put("onDutyState", MapUtil.mapper("id", item.get("ON_DUTY_STATE"),
                    "description", item.get("ON_DUTY_STATE_NAME")));
            m.put("company", MapUtil.mapper("id", item.get("COMPANY_ID"),
                    "name", item.get("COMPANY_NAME")));
            return MapUtil.mapper("employee", m,
                    "id", item.get("ID"),
                    "innerBusinessKey", item.get("ID"),
                    "name", item.get("NAME"));
        }).collect(Collectors.toList());
    }

    /**
     * 根据门店查询店长
     * @param request
     * @return
     */
    public Employee findByWorkBranchAndPostEQManager(SimpleRequest request){
        String id = request.get("id");
        List<Employee> byWorkBranchAndPostEQManager = employeeRepository.findByWorkBranchAndPostEQManager(id);
        if (byWorkBranchAndPostEQManager.isEmpty())return null;
        return byWorkBranchAndPostEQManager.stream().findFirst().get();
    }
}
